<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>PDF预览</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            overflow: hidden;
        }

        #header {
            height: 50px;
            background-color: #f0f0f0;
            display: flex;
            align-items: center;
            padding: 0 20px;
            border-bottom: 1px solid #ccc;
            justify-content: space-between;
        }

        #title {
            font-size: 18px;
            font-weight: bold;
            text-align: center;
            flex-grow: 1;
            margin: 0 20px;
        }

        #menuBtn {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        #menuBtn:hover {
            background-color: #0056b3;
        }

        #downloadBtn {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        #downloadBtn:hover {
            background-color: #0056b3;
        }

        #container {
            display: flex;
            height: calc(100vh - 50px);
        }

        #sidebar {
            width: 200px;
            background-color: #f8f9fa;
            border-right: 1px solid #ddd;
            overflow-y: auto;
            padding: 10px;
            transition: all 0.3s ease;
            flex-shrink: 0;
        }

        #sidebar.hidden {
            width: 0;
            padding: 0;
            border-right: none;
            overflow: hidden;
        }

        #thumbnailList {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .thumbnail-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            display: flex;
            align-items: center;
        }

        .thumbnail-item:hover {
            background-color: #e9ecef;
        }

        .thumbnail-item.active {
            background-color: #007bff;
            color: white;
        }

        .thumbnail-page {
            margin-right: 10px;
            font-weight: bold;
        }

        .thumbnail-img {
            width: 60px;
            height: 80px;
            object-fit: cover;
            border: 1px solid #ccc;
        }

        #mainContent {
            flex: 1;
            display: flex;
            flex-direction: column;
            position: relative;
            height: 100%;
            max-height: 100%;
            overflow: hidden;
        }

        #toolbar {
            padding: 10px;
            background-color: #f8f9fa;
            border-bottom: 1px solid #ddd;
            display: flex;
            justify-content: center;
            gap: 15px;
            flex-wrap: wrap;
            align-items: center;
        }

        .toolbar-group {
            display: flex;
            gap: 3px;
            align-items: center;
            background: white;
            border: 1px solid #ddd;
            border-radius: 6px;
            padding: 2px;
        }

        .toolbar-btn {
            padding: 8px 12px;
            background-color: transparent;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s ease;
            white-space: nowrap;
        }

        .toolbar-btn:hover {
            background-color: #e9ecef;
        }

        .toolbar-btn.active {
            background-color: #007bff;
            color: white;
        }

        .toolbar-btn.compact {
            padding: 8px 10px;
            font-size: 16px;
            min-width: 36px;
        }

        .mode-btn {
            min-width: 50px;
        }

        .page-info {
            padding: 8px 12px;
            font-size: 14px;
            color: #666;
            white-space: nowrap;
            background: #f8f9fa;
            border-radius: 4px;
            margin: 0 4px;
        }

        /* 缩放组样式 */
        .zoom-group {
            position: relative;
        }

        .zoom-select {
            padding: 6px 8px;
            border: none;
            border-radius: 4px;
            background: #f8f9fa;
            font-size: 14px;
            cursor: pointer;
            min-width: 100px;
            margin: 0 2px;
        }

        .zoom-select:focus {
            outline: 2px solid #007bff;
            outline-offset: -2px;
        }

        /* 绘图工具组样式 */
        .draw-group {
            position: relative;
        }

        .toggle-btn {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            border-radius: 6px;
            font-weight: 500;
        }

        .toggle-btn:hover {
            background: linear-gradient(135deg, #218838, #1ea087);
            transform: translateY(-1px);
        }

        .draw-tools-panel {
            position: absolute;
            top: 100%;
            left: 0;
            background: white;
            border: 1px solid #ddd;
            border-radius: 6px;
            padding: 8px;
            display: none;
            z-index: 1000;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            gap: 4px;
            align-items: center;
        }

        .draw-tools-panel.show {
            display: flex;
        }

        .draw-tool {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: white;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.2s ease;
            min-width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .draw-tool:hover {
            background: #f0f0f0;
            transform: translateY(-1px);
        }

        .draw-tool.active {
            background: #28a745;
            color: white;
            border-color: #28a745;
        }

        /* 橡皮擦工具特殊样式 */
        .draw-tool[data-tool="eraser"].active {
            background: #dc3545;
            color: white;
            border-color: #dc3545;
        }

        .draw-tool[data-tool="eraser"]:hover {
            background: #f8d7da;
            border-color: #dc3545;
        }

        /* 撤销和重做工具样式 */
        .draw-tool[data-tool="undo"],
        .draw-tool[data-tool="redo"] {
            background: #f8f9fa;
            border-color: #6c757d;
        }

        .draw-tool[data-tool="undo"]:hover,
        .draw-tool[data-tool="redo"]:hover {
            background: #e9ecef;
            border-color: #495057;
        }

        .draw-tool[data-tool="undo"]:disabled,
        .draw-tool[data-tool="redo"]:disabled {
            background: #f8f9fa !important;
            color: #6c757d !important;
            border-color: #dee2e6 !important;
            cursor: not-allowed;
            opacity: 0.5;
        }

        .color-picker {
            width: 36px;
            height: 36px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            padding: 0;
            background: none;
        }

        .clear-btn {
            padding: 8px;
            border: 1px solid #dc3545;
            border-radius: 4px;
            background: #dc3545;
            color: white;
            cursor: pointer;
            font-size: 16px;
            min-width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }

        .clear-btn:hover {
            background: #c82333;
            transform: translateY(-1px);
        }

        /* 清除下拉菜单样式 */
        .clear-dropdown {
            position: relative;
        }

        .clear-dropdown-menu {
            position: absolute;
            top: 100%;
            right: 0;
            background: white;
            border: 1px solid #ddd;
            border-radius: 6px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            display: none;
            flex-direction: column;
            z-index: 1000;
            min-width: 120px;
            overflow: hidden;
        }

        .clear-dropdown-menu.show {
            display: flex;
        }

        .clear-option {
            padding: 10px 15px;
            border: none;
            background: white;
            color: #333;
            cursor: pointer;
            font-size: 14px;
            text-align: left;
            transition: all 0.2s ease;
            border-bottom: 1px solid #eee;
        }

        .clear-option:last-child {
            border-bottom: none;
        }

        .clear-option:hover {
            background: #f8f9fa;
            color: #dc3545;
        }

        .clear-option:active {
            background: #e9ecef;
        }

        .toolbar-btn:disabled {
            background-color: #f8f9fa;
            color: #6c757d;
            border-color: #dee2e6;
            cursor: not-allowed;
            opacity: 0.6;
        }

        .toolbar-btn:disabled:hover {
            background-color: #f8f9fa;
        }

        #pdfContainer {
            flex: 1;
            overflow: auto;
            position: relative;
            width: 100%;
            height: 100%;
            max-width: 100%;
            max-height: 100%;
        }

        #pdfViewer {
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            max-width: 100%;
            max-height: 100%;
        }

        .pdf-canvas {
            margin: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            flex-shrink: 0;
            /* 防止canvas被压缩 */
        }

        /* 翻页区域样式 - 优化尺寸以减少对绘画功能的影响 */
        .flip-area {
            position: absolute;
            top: 0;
            height: 100%;
            width: 60px;
            /* 从20%改为固定60px，减少对绘画的影响 */
            z-index: 10;
            transition: background-color 0.2s ease;
        }

        #prevArea {
            left: 0;
            cursor: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="%23007bff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15,18 9,12 15,6"></polyline></svg>') 12 12, pointer;
        }

        #nextArea {
            right: 0;
            cursor: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="%23007bff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9,18 15,12 9,6"></polyline></svg>') 12 12, pointer;
        }

        /* 鼠标悬停时显示半透明背景提示 */
        .flip-area:hover {
            background-color: rgba(0, 123, 255, 0.1);
        }

        /* 翻页区域禁用状态 */
        .flip-area.disabled {
            cursor: not-allowed !important;
            pointer-events: none;
        }

        .flip-area.disabled:hover {
            background-color: transparent;
        }

        /* 加载状态下的翻页区域 */
        .flip-area:not(.disabled):active {
            background-color: rgba(0, 123, 255, 0.2);
        }

        /* 在小屏幕上保持合适的翻页区域宽度，确保触控友好 */
        @media (max-width: 768px) {
            .flip-area {
                width: 80px;
                /* 小屏幕上增加到80px以优化触控体验 */
            }
        }

        /* 绘图模式下进一步缩小翻页区域，最大化绘画空间 */
        .drawing-mode .flip-area {
            width: 40px;
            /* 绘图时翻页区域缩小到40px */
            pointer-events: auto;
            /* 保持翻页功能可用 */
            z-index: 2;
            /* 降低层级，让绘图画布优先 */
        }

        .drawing-mode .flip-area:hover {
            background-color: rgba(0, 123, 255, 0.05);
            /* 绘图模式下减弱悬停效果 */
        }

        /* 小屏幕下的绘图模式调整 */
        @media (max-width: 768px) {
            .drawing-mode .flip-area {
                width: 50px;
                /* 小屏幕绘图模式下保持50px */
            }
        }

        /* 绘图功能样式 */
        .draw-canvas {
            position: absolute;
            top: 0;
            left: 0;
            pointer-events: none;
            z-index: 5;
        }

        .draw-canvas.drawing {
            pointer-events: auto;
        }

        .color-picker::-webkit-color-swatch-wrapper {
            padding: 0;
        }

        .color-picker::-webkit-color-swatch {
            border: none;
            border-radius: 3px;
        }

        /* 绘图模式下的鼠标样式 */
        .drawing-mode {
            cursor: crosshair;
        }

        /* 橡皮擦模式下的特殊鼠标样式 */
        .eraser-mode {
            cursor: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="%23dc3545" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.5l9.4-9.4c1-1 2.5-1 3.5 0l5.9 5.9c1 1 1 2.5 0 3.5L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg>') 12 12, auto;
        }

        /* 加载动画样式 */
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.9);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            backdrop-filter: blur(2px);
        }

        .loading-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 20px;
        }

        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        .loading-text {
            font-size: 16px;
            color: #666;
            font-weight: bold;
        }

        .loading-progress {
            width: 200px;
            height: 6px;
            background-color: #e9ecef;
            border-radius: 3px;
            overflow: hidden;
        }

        .loading-progress-bar {
            height: 100%;
            background-color: #007bff;
            border-radius: 3px;
            transition: width 0.3s ease;
            width: 0%;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        /* 隐藏加载动画 */
        .loading-overlay.hidden {
            display: none;
        }

        /* 全屏模式样式 */
        .fullscreen-mode #header {
            position: fixed;
            top: -60px;
            /* 隐藏到屏幕上方 */
            left: 0;
            right: 0;
            z-index: 1000;
            transition: top 0.3s ease;
            pointer-events: auto;
        }

        .fullscreen-mode #header.show {
            top: 0;
            /* 显示标题栏 */
        }

        .fullscreen-mode #toolbar {
            position: fixed;
            top: -60px;
            /* 隐藏到屏幕上方 */
            left: 0;
            right: 0;
            z-index: 999;
            transition: top 0.3s ease;
            pointer-events: auto;
            background-color: #f8f9fa;
            border-bottom: 1px solid #ddd;
        }

        .fullscreen-mode #toolbar.show {
            top: 50px;
            /* 显示在标题栏下方 */
        }

        .fullscreen-mode #sidebar {
            position: fixed;
            left: -220px;
            /* 隐藏到屏幕左侧 */
            top: 0;
            bottom: 0;
            z-index: 998;
            transition: left 0.3s ease;
            pointer-events: auto;
            width: 200px;
            background-color: #f8f9fa;
        }

        .fullscreen-mode #sidebar.show {
            left: 0;
            /* 显示目录栏 */
        }

        .fullscreen-mode #container {
            height: 100vh;
        }

        .fullscreen-mode #mainContent {
            height: 100vh !important;
            max-height: 100vh !important;
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            bottom: 0 !important;
            z-index: 1 !important;
            margin-top: 0;
        }

        /* 鼠标感应区域 */
        .fullscreen-trigger {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: 80px;
            z-index: 500;
            background: transparent;
            display: none;
            pointer-events: auto;
        }

        .fullscreen-mode .fullscreen-trigger {
            display: block;
        }

        .fullscreen-mode .toolbar-btn {
            pointer-events: auto;
            cursor: pointer;
        }

        .fullscreen-mode .toolbar-btn:hover {
            background-color: #e9ecef;
        }

        .fullscreen-mode .toolbar-btn.active {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }

        .fullscreen-mode .toolbar-btn:disabled {
            pointer-events: none;
            cursor: not-allowed;
        }

        /* 全屏模式下PDF容器正确调整 */
        .fullscreen-mode #pdfContainer {
            height: 100vh !important;
            width: 100vw !important;
            max-height: 100vh !important;
            max-width: 100vw !important;
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            bottom: 0 !important;
            overflow: auto !important;
            background: #f5f5f5 !important;
        }

        .fullscreen-mode #pdfViewer {
            height: 100% !important;
            width: 100% !important;
            min-height: 100vh !important;
            display: flex !important;
            justify-content: center !important;
            align-items: center !important;
        }

        /* 右键菜单样式 */
        .context-menu {
            position: fixed;
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            padding: 8px 0;
            z-index: 10000;
            min-width: 200px;
            max-width: 280px;
            display: none;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            font-size: 14px;
        }

        .context-menu.show {
            display: block;
            animation: contextMenuSlideIn 0.15s ease-out;
        }

        @keyframes contextMenuSlideIn {
            from {
                opacity: 0;
                transform: scale(0.95) translateY(-5px);
            }

            to {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }

        .context-menu-item {
            padding: 10px 16px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 12px;
            color: #333;
            transition: all 0.2s ease;
            border: none;
            background: none;
            text-align: left;
            font-size: 14px;
            white-space: nowrap;
        }

        .context-menu-item:hover {
            background: #f0f7ff;
            color: #007bff;
        }

        .context-menu-item:active {
            background: #e3f2fd;
        }

        .context-menu-item.disabled {
            color: #999;
            cursor: not-allowed;
            opacity: 0.5;
            pointer-events: none;
        }

        .context-menu-item.disabled:hover {
            background: none;
            color: #999;
        }

        .context-menu-divider {
            height: 1px;
            background: #eee;
            margin: 6px 0;
        }

        .context-menu-submenu {
            position: relative;
        }

        .context-menu-submenu::after {
            content: '▶';
            margin-left: auto;
            margin-right: 4px;
            font-size: 12px;
            color: #666;
        }

        .context-submenu {
            position: absolute;
            left: 100%;
            top: 0;
            background: white;
            border: 1px solid #ddd;
            border-radius: 6px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            padding: 6px 0;
            min-width: 180px;
            max-width: 250px;
            display: none;
            z-index: 10001;
        }

        .context-menu-submenu:hover .context-submenu {
            display: block;
            animation: contextMenuSlideIn 0.1s ease-out;
        }

        /* 子菜单智能定位 - 向上显示 */
        .context-submenu.position-up {
            bottom: 0;
            top: auto;
        }

        /* 子菜单智能定位 - 向左显示 */
        .context-submenu.position-left {
            left: auto;
            right: 100%;
        }

        .context-menu-icon {
            width: 16px;
            height: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .context-menu-text {
            flex: 1;
        }

        .context-menu-shortcut {
            font-size: 12px;
            color: #666;
            margin-left: auto;
        }
    </style>
</head>

<body>
    <!-- 全屏模式下的鼠标感应区域 -->
    <div class="fullscreen-trigger" id="fullscreenTrigger"></div>

    <div id="header">
        <button id="menuBtn">目录</button>
        <div id="title">PDF预览</div>
        <button id="downloadBtn">下载</button>
    </div>
    <div id="container">
        <div id="sidebar">
            <ul id="thumbnailList"></ul>
        </div>
        <div id="mainContent">
            <div id="toolbar">
                <!-- 翻页控制组 -->
                <div class="toolbar-group">
                    <button id="firstPage" class="toolbar-btn compact">⇤</button>
                    <button id="prevPage" class="toolbar-btn compact">◀</button>
                    <span id="pageInfo" class="page-info">第 <span id="currentPage">1</span> / <span
                            id="totalPages">0</span> 页</span>
                    <button id="nextPage" class="toolbar-btn compact">▶</button>
                    <button id="lastPage" class="toolbar-btn compact">⇥</button>
                </div>

                <!-- 显示模式组 -->
                <div class="toolbar-group">
                    <button id="singlePage" class="toolbar-btn mode-btn active">单页</button>
                    <button id="doublePage" class="toolbar-btn mode-btn">双页</button>
                </div>

                <!-- 缩放控制组 -->
                <div class="toolbar-group zoom-group">
                    <button id="zoomOut" class="toolbar-btn compact">-</button>
                    <select id="zoomSelect" class="zoom-select">
                        <option value="fit">适应屏幕</option>
                        <option value="width">适应宽度</option>
                        <option value="50">50%</option>
                        <option value="75">75%</option>
                        <option value="100">100%</option>
                        <option value="125">125%</option>
                        <option value="150">150%</option>
                        <option value="200">200%</option>
                    </select>
                    <button id="zoomIn" class="toolbar-btn compact">+</button>
                </div>

                <!-- 绘图工具组 -->
                <div class="toolbar-group draw-group">
                    <button id="drawToggle" class="toolbar-btn toggle-btn">✏️ 标记</button>
                    <div id="drawTools" class="draw-tools-panel">
                        <button id="drawPen" class="draw-tool" data-tool="pen" title="画笔">✏️</button>
                        <button id="drawLine" class="draw-tool" data-tool="line" title="直线">📏</button>
                        <button id="drawRect" class="draw-tool" data-tool="rectangle" title="矩形">⬜</button>
                        <button id="drawCircle" class="draw-tool" data-tool="circle" title="圆形">⭕</button>
                        <button id="drawArrow" class="draw-tool" data-tool="arrow" title="箭头">➡️</button>
                        <button id="drawUndo" class="draw-tool" data-tool="undo" title="撤销">↶</button>
                        <button id="drawRedo" class="draw-tool" data-tool="redo" title="重做">↷</button>
                        <button id="drawEraser" class="draw-tool" data-tool="eraser" title="橡皮擦">🧹</button>
                        <input type="color" id="drawColor" class="color-picker" value="#ff0000" title="选择颜色">
                        <div class="clear-dropdown">
                            <button id="clearDropdownBtn" class="clear-btn" title="清除标记">🗑️ ▼</button>
                            <div id="clearDropdownMenu" class="clear-dropdown-menu">
                                <button id="clearCurrentPage" class="clear-option">清除当前页</button>
                                <button id="clearAllPages" class="clear-option">清除所有页</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 功能按钮组 -->
                <div class="toolbar-group">
                    <button id="fullscreenBtn" class="toolbar-btn">全屏</button>
                </div>
            </div>
            <div id="pdfContainer">
                <!-- 加载动画 -->
                <div id="loadingOverlay" class="loading-overlay">
                    <div class="loading-content">
                        <div class="loading-spinner"></div>
                        <div id="loadingText" class="loading-text">正在加载PDF文档...</div>
                        <div class="loading-progress">
                            <div id="loadingProgressBar" class="loading-progress-bar"></div>
                        </div>
                    </div>
                </div>
                <div id="pdfViewer"></div>
                <!-- 绘图画布 -->
                <canvas id="drawCanvas" class="draw-canvas"></canvas>
                <!-- 翻页区域 -->
                <div id="prevArea" class="flip-area"></div>
                <div id="nextArea" class="flip-area"></div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
    <script>
        // 设置PDF.js的worker路径
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js';

        // 获取URL参数
        const urlParams = new URLSearchParams(window.location.search);
        const pdfPath = urlParams.get('file');
        const title = urlParams.get('title');

        // 设置标题
        function generateDetailedTitle(pdfPath, originalTitle) {
            if (!pdfPath) return originalTitle || 'PDF预览';

            // 从路径中提取信息
            const pathParts = pdfPath.split('/');
            let detailedTitle = '';

            // 查找学段、学科、版本信息
            let segment = ''; // 学段
            let subject = ''; // 学科
            let version = ''; // 版本

            for (let i = 0; i < pathParts.length; i++) {
                const part = pathParts[i];

                // 识别学段（小学、初中、高中等）
                if (part.includes('小学') || part.includes('初中') || part.includes('高中') || part.includes('大学')) {
                    segment = part;
                }

                // 识别学科（数学、语文、英语等）
                if (i > 0 && pathParts[i - 1] && pathParts[i - 1].includes('学') &&
                    !版本关键词.some(keyword => part.includes(keyword)) &&
                    !part.includes('.pdf')) {
                    subject = part;
                }

                // 识别版本（人教版、统编版等）
                if (版本关键词.some(keyword => part.includes(keyword))) {
                    version = part;
                }
            }

            // 组合标题
            const titleParts = [];
            if (segment) titleParts.push(segment);
            if (subject) titleParts.push(subject);
            if (version) titleParts.push(version);
            if (originalTitle) titleParts.push(originalTitle);

            return titleParts.length > 0 ? titleParts.join(' - ') : (原有title || 'PDF预览');
        }

        // 版本关键词列表
        const 版本关键词 = ['版', '社版', '出版社', '编写组', '编著', '主编'];

        // 设置标题
        const detailedTitle = generateDetailedTitle(pdfPath, title);
        document.getElementById('title').textContent = detailedTitle;

        // 设置下载链接
        if (pdfPath) {
            document.getElementById('downloadBtn').addEventListener('click', function () {
                // 创建一个隐藏的a标签来触发下载
                const link = document.createElement('a');
                link.href = pdfPath;

                // 优先使用页面标题作为文件名，如果没有页面标题则使用URL参数中的title，最后回退到路径提取
                let fileName;
                const pageTitle = document.getElementById('title').textContent;
                if (pageTitle && pageTitle.trim() && pageTitle !== 'PDF预览') {
                    // 使用页面显示的完整标题作为文件名，确保以.pdf结尾
                    fileName = pageTitle.trim();
                    if (!fileName.toLowerCase().endsWith('.pdf')) {
                        fileName += '.pdf';
                    }
                } else if (title && title.trim()) {
                    // fallback 1：使用URL参数中的title
                    fileName = title.trim();
                    if (!fileName.toLowerCase().endsWith('.pdf')) {
                        fileName += '.pdf';
                    }
                } else {
                    // fallback 2：从路径提取文件名
                    fileName = pdfPath.split('/').pop() || 'document.pdf';
                }

                link.download = fileName;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            });
        }

        let pdfDoc = null;
        let currentPage = 1;
        let scale = 1.0;
        let zoomMode = 'fit'; // 'fit', 'width', 'custom'
        let viewMode = 'single'; // 'single' or 'double'
        let isFullscreen = false;
        let isLoading = false; // 加载状态标记

        // 绘图功能相关变量
        let isDrawing = false;
        let currentTool = null;
        let drawColor = '#ff0000';
        let startX, startY;
        let drawCanvas = null;
        let drawCtx = null;
        let pageDrawings = {}; // 按页面存储绘图数据
        let drawings = []; // 当前页面的绘图数据（向后兼容）

        // 撤销重做功能变量
        let drawingHistory = []; // 当前页面的历史记录
        let historyIndex = -1; // 当前历史记录位置
        let maxHistoryLength = 50; // 最大历史记录数

        // 加载管理函数
        function showLoading(text = '正在加载...', progress = 0) {
            const overlay = document.getElementById('loadingOverlay');
            const textElement = document.getElementById('loadingText');
            const progressBar = document.getElementById('loadingProgressBar');

            isLoading = true;
            overlay.classList.remove('hidden');
            textElement.textContent = text;
            progressBar.style.width = progress + '%';

            // 加载时禁用翻页区域
            const prevArea = document.getElementById('prevArea');
            const nextArea = document.getElementById('nextArea');
            if (prevArea) prevArea.style.pointerEvents = 'none';
            if (nextArea) nextArea.style.pointerEvents = 'none';
        }

        function hideLoading() {
            const overlay = document.getElementById('loadingOverlay');
            isLoading = false;
            overlay.classList.add('hidden');

            // 恢复翻页区域交互
            const prevArea = document.getElementById('prevArea');
            const nextArea = document.getElementById('nextArea');
            if (prevArea) prevArea.style.pointerEvents = 'auto';
            if (nextArea) nextArea.style.pointerEvents = 'auto';

            // 更新翻页区域状态
            if (typeof updateFlipAreaStatus === 'function') {
                updateFlipAreaStatus();
            }
        }

        function updateLoadingProgress(progress, text) {
            if (!isLoading) return;

            const textElement = document.getElementById('loadingText');
            const progressBar = document.getElementById('loadingProgressBar');

            if (text) textElement.textContent = text;
            progressBar.style.width = Math.min(100, Math.max(0, progress)) + '%';
        }

        // 加载PDF文档
        if (pdfPath) {
            showLoading('正在加载PDF文档...', 10);

            // 创建加载任务，支持进度监控
            const loadingTask = pdfjsLib.getDocument({
                url: pdfPath,
                // 启用分段加载以提高性能
                rangeChunkSize: 65536, // 64KB
                disableAutoFetch: false, // 自动获取页面
                disableStream: false, // 启用流式加载
                disableFontFace: false, // 启用字体加载
            });

            // 监听加载进度
            loadingTask.onProgress = function (progressData) {
                if (progressData.total > 0) {
                    const progress = (progressData.loaded / progressData.total) * 60; // 文档加载占总进度60%
                    updateLoadingProgress(10 + progress, `正在加载 PDF 文档... ${Math.round(progress)}%`);
                }
            };

            loadingTask.promise.then(function (pdf) {
                updateLoadingProgress(70, '正在初始化页面...');

                pdfDoc = pdf;
                // 设置总页数
                document.getElementById('totalPages').textContent = pdf.numPages;

                updateLoadingProgress(80, '正在渲染首页...');

                // 渲染首页
                renderPage(currentPage).then(() => {
                    updateLoadingProgress(90, '正在生成目录...');

                    // 异步生成缩略图，不阻塞首页显示
                    setTimeout(() => {
                        generateThumbnails(pdf).then(() => {
                            updateLoadingProgress(100, '加载完成');
                            // 设置默认缩放模式
                            updateZoomSelect();
                            setTimeout(hideLoading, 500); // 稍微延迟隐藏加载动画
                        });
                    }, 100);
                });
            }).catch(function (error) {
                console.error('加载PDF失败:', error);
                updateLoadingProgress(0, '加载失败');
                setTimeout(() => {
                    hideLoading();
                    alert('PDF加载失败，请检查文件路径是否正确');
                }, 1000);
            });
        } else {
            hideLoading();
        }

        // 目录按钮事件处理函数
        function handleMenuBtnClick() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('hidden');
        }

        // 初始化目录按钮事件
        document.getElementById('menuBtn').addEventListener('click', handleMenuBtnClick);

        // 全屏按钮事件
        document.getElementById('fullscreenBtn').addEventListener('click', function () {
            const elem = document.documentElement;
            if (!isFullscreen) {
                if (elem.requestFullscreen) {
                    elem.requestFullscreen();
                } else if (elem.mozRequestFullScreen) { /* Firefox */
                    elem.mozRequestFullScreen();
                } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
                    elem.webkitRequestFullscreen();
                } else if (elem.msRequestFullscreen) { /* IE/Edge */
                    elem.msRequestFullscreen();
                }
                this.textContent = '退出全屏';
                isFullscreen = true;
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.mozCancelFullScreen) { /* Firefox */
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) { /* Chrome, Safari & Opera */
                    document.webkitExitFullscreen();
                } else if (document.msExitFullscreen) { /* IE/Edge */
                    document.msExitFullscreen();
                }
                this.textContent = '全屏阅读';
                isFullscreen = false;
            }
        });

        // 监听全屏状态变化
        document.addEventListener('fullscreenchange', handleFullscreenChange);
        document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
        document.addEventListener('mozfullscreenchange', handleFullscreenChange);
        document.addEventListener('MSFullscreenChange', handleFullscreenChange);

        // 键盘控制翻页功能
        document.addEventListener('keydown', function (e) {
            // 如果正在加载中，不响应键盘事件
            if (isLoading) return;

            // 如果焦点在输入框中，不响应键盘事件
            if (document.activeElement.tagName === 'INPUT' ||
                document.activeElement.tagName === 'TEXTAREA' ||
                document.activeElement.isContentEditable) {
                return;
            }

            // 防止默认的键盘滚动行为
            const preventDefaultKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];
            if (preventDefaultKeys.includes(e.key)) {
                e.preventDefault();
            }

            switch (e.key) {
                case 'ArrowUp':    // 上箭头 - 上一页
                case 'ArrowLeft':  // 左箭头 - 上一页
                    handlePrevPage();
                    break;

                case 'ArrowDown':  // 下箭头 - 下一页
                case 'ArrowRight': // 右箭头 - 下一页
                    handleNextPage();
                    break;

                case 'Home':       // Home键 - 首页
                    handleFirstPage();
                    break;

                case 'End':        // End键 - 尾页
                    handleLastPage();
                    break;
            }
        });

        // 封装翻页函数，供按钮和键盘共用
        function handlePrevPage() {
            if (!pdfDoc || isLoading) return;

            // 检查翻页区域是否被禁用
            const prevArea = document.getElementById('prevArea');
            if (prevArea && prevArea.classList.contains('disabled')) return;

            clearDrawingsOnPageChange(); // 清除绘图

            if (viewMode === 'single') {
                if (currentPage > 1) {
                    currentPage--;
                    showLoading('正在加载第' + currentPage + '页...', 50);
                    renderPage(currentPage).then(() => {
                        updateThumbnailHighlight();
                        hideLoading();
                    });
                }
            } else {
                // 双页模式下，向前翻两页
                if (currentPage > 2) {
                    currentPage -= 2;
                    showLoading('正在加载第' + currentPage + '-' + (currentPage + 1) + '页...', 50);
                    renderPage(currentPage).then(() => {
                        updateThumbnailHighlight();
                        hideLoading();
                    });
                } else if (currentPage > 1) {
                    currentPage = 1;
                    showLoading('正在加载第' + currentPage + '页...', 50);
                    renderPage(currentPage).then(() => {
                        updateThumbnailHighlight();
                        hideLoading();
                    });
                }
            }
        }

        function handleNextPage() {
            if (!pdfDoc || isLoading) return;

            // 检查翻页区域是否被禁用
            const nextArea = document.getElementById('nextArea');
            if (nextArea && nextArea.classList.contains('disabled')) return;

            clearDrawingsOnPageChange(); // 清除绘图

            if (viewMode === 'single') {
                if (currentPage < pdfDoc.numPages) {
                    currentPage++;
                    showLoading('正在加载第' + currentPage + '页...', 50);
                    renderPage(currentPage).then(() => {
                        updateThumbnailHighlight();
                        hideLoading();
                    });
                }
            } else {
                // 双页模式下，向后翻两页
                if (currentPage < pdfDoc.numPages - 1) {
                    currentPage += 2;
                    showLoading('正在加载第' + currentPage + '-' + Math.min(currentPage + 1, pdfDoc.numPages) + '页...', 50);
                    renderPage(currentPage).then(() => {
                        updateThumbnailHighlight();
                        hideLoading();
                    });
                } else if (currentPage < pdfDoc.numPages) {
                    currentPage = pdfDoc.numPages;
                    showLoading('正在加载第' + currentPage + '页...', 50);
                    renderPage(currentPage).then(() => {
                        updateThumbnailHighlight();
                        hideLoading();
                    });
                }
            }
        }

        function handleFirstPage() {
            if (!pdfDoc || isLoading || currentPage === 1) return;

            clearDrawingsOnPageChange(); // 清除绘图
            currentPage = 1;
            showLoading('正在跳转到首页...', 50);
            renderPage(currentPage).then(() => {
                updateThumbnailHighlight();
                hideLoading();
            });
        }

        function handleLastPage() {
            if (!pdfDoc || isLoading || currentPage === pdfDoc.numPages) return;

            clearDrawingsOnPageChange(); // 清除绘图
            currentPage = pdfDoc.numPages;
            showLoading('正在跳转到尾页...', 50);
            renderPage(currentPage).then(() => {
                updateThumbnailHighlight();
                hideLoading();
            });
        }

        function handleFullscreenChange() {
            const fullscreenBtn = document.getElementById('fullscreenBtn');
            const body = document.body;
            const header = document.getElementById('header');
            const toolbar = document.getElementById('toolbar');
            const sidebar = document.getElementById('sidebar');
            const trigger = document.getElementById('fullscreenTrigger');

            if (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) {
                fullscreenBtn.textContent = '退出全屏';
                isFullscreen = true;

                // 进入全屏模式
                body.classList.add('fullscreen-mode');

                // 初始状态下隐藏所有界面元素
                header.classList.remove('show');
                toolbar.classList.remove('show');
                sidebar.classList.remove('show');

                // 设置鼠标感应事件
                setupFullscreenMouseEvents();

                // 延迟重新渲染页面以适应新的尺寸
                setTimeout(() => {
                    if (pdfDoc && currentPage) {
                        renderPage(currentPage).then(() => {
                            updateThumbnailHighlight();
                        });
                    }
                }, 100);

            } else {
                fullscreenBtn.textContent = '全屏阅读';
                isFullscreen = false;

                // 退出全屏模式
                body.classList.remove('fullscreen-mode');

                // 恢复所有界面元素显示
                header.classList.remove('show');
                toolbar.classList.remove('show');
                sidebar.classList.remove('show');

                // 清理鼠标事件监听
                cleanupFullscreenMouseEvents();

                // 延迟重新渲染页面以适应新的尺寸
                setTimeout(() => {
                    if (pdfDoc && currentPage) {
                        renderPage(currentPage).then(() => {
                            updateThumbnailHighlight();
                        });
                    }
                }, 100);
            }
        }

        // 上一页按钮事件
        document.getElementById('prevPage').addEventListener('click', function () {
            handlePrevPage();
        });

        // 下一页按钮事件
        document.getElementById('nextPage').addEventListener('click', function () {
            handleNextPage();
        });

        // 首页按钮事件
        document.getElementById('firstPage').addEventListener('click', function () {
            handleFirstPage();
        });

        // 尾页按钮事件
        document.getElementById('lastPage').addEventListener('click', function () {
            handleLastPage();
        });

        // 单页/双页切换
        document.getElementById('singlePage').addEventListener('click', function () {
            viewMode = 'single';
            this.classList.add('active');
            document.getElementById('doublePage').classList.remove('active');
            renderPage(currentPage);
            updateThumbnailHighlight();
        });

        document.getElementById('doublePage').addEventListener('click', function () {
            viewMode = 'double';
            this.classList.add('active');
            document.getElementById('singlePage').classList.remove('active');
            renderPage(currentPage);
            updateThumbnailHighlight();
        });

        // 缩放控制
        document.getElementById('zoomOut').addEventListener('click', function () {
            scale *= 0.9;
            zoomMode = 'custom';
            updateZoomSelect();
            renderPage(currentPage);
        });

        document.getElementById('zoomIn').addEventListener('click', function () {
            scale *= 1.1;
            zoomMode = 'custom';
            updateZoomSelect();
            renderPage(currentPage);
        });

        // 缩放下拉菜单
        document.getElementById('zoomSelect').addEventListener('change', function () {
            const value = this.value;
            if (value === 'fit') {
                zoomMode = 'fit';
            } else if (value === 'width') {
                zoomMode = 'width';
            } else {
                const percent = parseInt(value);
                scale = percent / 100;
                zoomMode = 'custom';
            }
            renderPage(currentPage);
        });

        // 更新缩放下拉菜单显示
        function updateZoomSelect() {
            const select = document.getElementById('zoomSelect');
            if (zoomMode === 'fit') {
                select.value = 'fit';
            } else if (zoomMode === 'width') {
                select.value = 'width';
            } else {
                const percent = Math.round(scale * 100);
                const option = select.querySelector(`option[value="${percent}"]`);
                if (option) {
                    select.value = percent.toString();
                } else {
                    // 添加自定义百分比选项
                    const customOption = document.createElement('option');
                    customOption.value = percent.toString();
                    customOption.textContent = percent + '%';
                    select.appendChild(customOption);
                    select.value = percent.toString();
                }
            }
        }

        // 绘图工具面板切换
        document.getElementById('drawToggle').addEventListener('click', function () {
            const panel = document.getElementById('drawTools');
            panel.classList.toggle('show');
        });

        // 点击其他地方关闭绘图面板
        document.addEventListener('click', function (e) {
            const drawGroup = document.querySelector('.draw-group');
            const panel = document.getElementById('drawTools');
            if (!drawGroup.contains(e.target)) {
                panel.classList.remove('show');
            }
        });

        // 点击左侧区域上一页
        document.getElementById('prevArea').addEventListener('click', function (e) {
            handlePrevPage();
        });

        // 点击右侧区域下一页
        document.getElementById('nextArea').addEventListener('click', function (e) {
            handleNextPage();
        });

        // 渲染页面
        function renderPage(pageNum) {
            return new Promise((resolve, reject) => {
                // 保存当前页面的绘图数据（使用旧的currentPage）
                const oldPage = currentPage;
                if (oldPage && oldPage !== pageNum) {
                    // 只有当页面发生变化时才保存
                    if (oldPage && drawings.length >= 0) {
                        pageDrawings[oldPage] = JSON.parse(JSON.stringify(drawings));
                        saveDrawingsToLocal();
                    }
                }

                // 更新当前页面号
                currentPage = pageNum;

                // 更平滑的过渡效果
                const pdfViewer = document.getElementById('pdfViewer');
                pdfViewer.style.transition = 'opacity 0.15s ease-in-out';
                pdfViewer.style.opacity = '0';

                // 减少延迟时间，使用更短的等待
                setTimeout(() => {
                    pdfViewer.innerHTML = '';

                    if (viewMode === 'single') {
                        renderSinglePage(pageNum).then(() => {
                            // 加载新页面的绘图数据
                            loadCurrentPageDrawings(pageNum);
                            pdfViewer.style.opacity = '1';
                            resolve();
                        }).catch(reject);
                    } else {
                        renderDoublePage(pageNum).then(() => {
                            // 加载新页面的绘图数据
                            loadCurrentPageDrawings(pageNum);
                            pdfViewer.style.opacity = '1';
                            resolve();
                        }).catch(reject);
                    }
                }, 30);
            });
        }

        // 渲染单页
        function renderSinglePage(pageNum) {
            return new Promise((resolve, reject) => {
                pdfDoc.getPage(pageNum).then(function (page) {
                    let viewport;

                    // 根据缩放模式计算缩放比例
                    if (zoomMode === 'fit') {
                        // 重置容器样式为默认状态
                        const pdfContainer = document.getElementById('pdfContainer');
                        pdfContainer.style.display = 'flex';
                        pdfContainer.style.justifyContent = 'center';
                        pdfContainer.style.alignItems = 'center';
                        pdfContainer.style.overflow = 'hidden'; // fit模式强制隐藏滚动条

                        const pdfViewer = document.getElementById('pdfViewer');
                        pdfViewer.style.display = 'flex';
                        pdfViewer.style.justifyContent = 'center';
                        pdfViewer.style.alignItems = 'center';
                        pdfViewer.style.flexDirection = 'column';
                        pdfViewer.style.minWidth = 'auto';
                        pdfViewer.style.minHeight = 'auto';
                        pdfViewer.style.padding = '0';

                        const container = document.getElementById('pdfContainer');
                        const containerWidth = container.clientWidth - 40;
                        const containerHeight = container.clientHeight - 40;

                        const pageWidth = page.view[2] - page.view[0];
                        const pageHeight = page.view[3] - page.view[1];

                        const scaleX = containerWidth / pageWidth;
                        const scaleY = containerHeight / pageHeight;

                        scale = Math.min(scaleX, scaleY);
                        viewport = page.getViewport({ scale: scale });
                    } else if (zoomMode === 'width') {
                        // 使用text-align方案彻底解决滚动与居中的冲突，但避免不必要的滚动条
                        const pdfContainer = document.getElementById('pdfContainer');

                        // 检查内容是否会超出容器
                        const container = document.getElementById('pdfContainer');
                        const containerWidth = container.clientWidth - 40;
                        const pageWidth = page.view[2] - page.view[0];
                        const calculatedScale = containerWidth / pageWidth;
                        const calculatedViewport = page.getViewport({ scale: calculatedScale });

                        // 如果内容高度不会超出容器，则使用fit模式的布局避免滚动条
                        if (calculatedViewport.height <= container.clientHeight - 40) {
                            pdfContainer.style.overflow = 'hidden';
                            pdfContainer.style.display = 'flex';
                            pdfContainer.style.justifyContent = 'center';
                            pdfContainer.style.alignItems = 'center';
                        } else {
                            // 内容超出时才使用滚动
                            pdfContainer.style.overflow = 'auto';
                            pdfContainer.style.display = 'block';
                            pdfContainer.style.textAlign = 'center'; // 使用text-align居中
                        }

                        pdfContainer.style.width = '100%';
                        pdfContainer.style.height = '100%';
                        pdfContainer.style.maxWidth = '100%';
                        pdfContainer.style.maxHeight = '100%';

                        // 重置pdfViewer为inline-block，利用text-align居中
                        const pdfViewer = document.getElementById('pdfViewer');
                        pdfViewer.style.display = 'inline-block';
                        pdfViewer.style.textAlign = 'left'; // 恢复内容的正常对齐
                        pdfViewer.style.verticalAlign = 'top';
                        pdfViewer.style.padding = '20px';
                        pdfViewer.style.width = 'auto';
                        pdfViewer.style.height = 'auto';
                        pdfViewer.style.minWidth = 'auto';
                        pdfViewer.style.minHeight = 'auto';

                        scale = calculatedScale;
                        viewport = calculatedViewport;
                    }
                    // 在自定义缩放模式下，使用正确的滚动与居中分离方案
                    else if (zoomMode === 'custom') {
                        // 重置pdfContainer为滚动容器
                        const pdfContainer = document.getElementById('pdfContainer');
                        pdfContainer.style.overflow = 'auto';
                        pdfContainer.style.width = '100%';
                        pdfContainer.style.height = '100%';
                        pdfContainer.style.maxWidth = '100%';
                        pdfContainer.style.maxHeight = '100%';
                        pdfContainer.style.display = 'block';
                        pdfContainer.style.textAlign = 'center'; // 使用text-align居中

                        // 重置pdfViewer为inline-block，利用text-align居中
                        const pdfViewer = document.getElementById('pdfViewer');
                        pdfViewer.style.display = 'inline-block';
                        pdfViewer.style.textAlign = 'left'; // 恢复内容的正常对齐
                        pdfViewer.style.verticalAlign = 'top';
                        pdfViewer.style.padding = '20px';
                        pdfViewer.style.width = 'auto';
                        pdfViewer.style.height = 'auto';
                        pdfViewer.style.minWidth = 'auto';
                        pdfViewer.style.minHeight = 'auto';

                        // 在自定义模式下，使用当前scale值创建viewport
                        viewport = page.getViewport({ scale: scale });
                    }

                    // 创建canvas元素来显示PDF
                    const canvas = document.createElement('canvas');
                    canvas.className = 'pdf-canvas';
                    const context = canvas.getContext('2d');

                    // 设置canvas尺寸
                    canvas.width = viewport.width;
                    canvas.height = viewport.height;

                    // 添加到容器
                    const pdfViewer = document.getElementById('pdfViewer');
                    pdfViewer.innerHTML = '';
                    pdfViewer.appendChild(canvas);

                    // 渲染PDF页面
                    const renderContext = {
                        canvasContext: context,
                        viewport: viewport
                    };

                    page.render(renderContext).promise.then(() => {
                        // 更新页面信息
                        document.getElementById('currentPage').textContent = pageNum;

                        // 更新导航按钮状态
                        document.getElementById('prevPage').disabled = (pageNum <= 1);
                        document.getElementById('nextPage').disabled = (pageNum >= pdfDoc.numPages);
                        document.getElementById('firstPage').disabled = (pageNum <= 1);
                        document.getElementById('lastPage').disabled = (pageNum >= pdfDoc.numPages);

                        // 更新绘图画布尺寸
                        setTimeout(() => {
                            if (typeof updateCanvasSize === 'function') {
                                updateCanvasSize();
                            }
                        }, 100);

                        resolve(); // 渲染完成
                    }).catch(reject);
                }).catch(reject);
            });
        }

        // 渲染双页
        function renderDoublePage(pageNum) {
            return new Promise((resolve, reject) => {
                // 确保页码是奇数（左侧页面）
                const leftPageNum = pageNum % 2 === 1 ? pageNum : pageNum - 1;
                const rightPageNum = leftPageNum + 1;

                // 清除pdfViewer的默认居中，改为水平排列
                const pdfViewer = document.getElementById('pdfViewer');
                const pdfContainer = document.getElementById('pdfContainer');

                // 在自定义缩放模式下，使用正确的滚动与居中分离方案
                if (zoomMode === 'custom') {
                    pdfContainer.style.overflow = 'auto';
                    pdfContainer.style.width = '100%';
                    pdfContainer.style.height = '100%';
                    pdfContainer.style.maxWidth = '100%';
                    pdfContainer.style.maxHeight = '100%';
                    pdfContainer.style.display = 'block';
                    pdfContainer.style.textAlign = 'center';

                    pdfViewer.style.display = 'flex';
                    pdfViewer.style.flexDirection = 'row';
                    pdfViewer.style.justifyContent = 'center';
                    pdfViewer.style.alignItems = 'flex-start';
                    pdfViewer.style.flexWrap = 'nowrap'; // 防止换行
                    pdfViewer.style.textAlign = 'left';
                    pdfViewer.style.verticalAlign = 'top';
                    pdfViewer.style.padding = '20px';
                    pdfViewer.style.width = 'auto';
                    pdfViewer.style.height = 'auto';
                    pdfViewer.style.minWidth = 'max-content'; // 确保能容纳两个页面
                } else {
                    // 非自定义模式下，统一使用flex布局确保不换行
                    if (zoomMode === 'fit') {
                        // fit模式使用flex布局
                        pdfContainer.style.display = 'flex';
                        pdfContainer.style.justifyContent = 'center';
                        pdfContainer.style.alignItems = 'center';
                        pdfContainer.style.textAlign = 'initial';
                        pdfContainer.style.overflow = 'hidden'; // fit模式强制隐藏滚动条

                        pdfViewer.style.display = 'flex';
                        pdfViewer.style.flexDirection = 'row';
                        pdfViewer.style.justifyContent = 'center';
                        pdfViewer.style.alignItems = 'center';
                        pdfViewer.style.flexWrap = 'nowrap'; // 防止换行
                    } else {
                        // width模式使用flex布局，确保不换行，避免滚动条
                        pdfContainer.style.overflow = 'hidden'; // width模式在双页下也隐藏滚动条
                        pdfContainer.style.width = '100%';
                        pdfContainer.style.height = '100%';
                        pdfContainer.style.maxWidth = '100%';
                        pdfContainer.style.maxHeight = '100%';
                        pdfContainer.style.display = 'flex';
                        pdfContainer.style.justifyContent = 'center';
                        pdfContainer.style.alignItems = 'center';

                        pdfViewer.style.display = 'flex';
                        pdfViewer.style.flexDirection = 'row';
                        pdfViewer.style.justifyContent = 'center';
                        pdfViewer.style.alignItems = 'center';
                        pdfViewer.style.flexWrap = 'nowrap'; // 防止换行
                        pdfViewer.style.padding = '10px'; // 减小padding避免溢出
                        pdfViewer.style.width = 'auto';
                        pdfViewer.style.height = 'auto';
                        pdfViewer.style.minWidth = 'auto'; // 改为auto，避免强制最大内容宽度
                        pdfViewer.style.maxWidth = '100%'; // 限制最大宽度
                    }

                    pdfViewer.style.textAlign = 'initial';
                    pdfViewer.style.verticalAlign = 'initial';
                }

                // 跟踪渲染完成的页面数量
                let completedPages = 0;
                const totalPages = rightPageNum <= pdfDoc.numPages ? 2 : 1;

                function checkComplete() {
                    completedPages++;
                    if (completedPages === totalPages) {
                        // 在双页模式下，确保currentPage与leftPageNum一致
                        currentPage = leftPageNum;

                        // 更新页面信息
                        document.getElementById('currentPage').textContent = leftPageNum;

                        // 更新导航按钮状态
                        document.getElementById('prevPage').disabled = (leftPageNum <= 1);
                        document.getElementById('nextPage').disabled = (rightPageNum >= pdfDoc.numPages);
                        document.getElementById('firstPage').disabled = (leftPageNum <= 1);
                        document.getElementById('lastPage').disabled = (rightPageNum >= pdfDoc.numPages);

                        // 更新绘图画布尺寸
                        setTimeout(() => {
                            if (typeof updateCanvasSize === 'function') {
                                updateCanvasSize();
                            }
                        }, 100);

                        resolve(); // 所有页面渲染完成
                    }
                }

                // 渲染左侧页面
                if (leftPageNum >= 1) {
                    pdfDoc.getPage(leftPageNum).then(function (page) {
                        let viewport;

                        // 根据缩放模式计算缩放比例
                        if (zoomMode === 'fit') {
                            const container = document.getElementById('pdfContainer');
                            const containerWidth = (container.clientWidth - 80) / 2; // 减去margin和间距
                            const containerHeight = container.clientHeight - 40;

                            const pageWidth = page.view[2] - page.view[0];
                            const pageHeight = page.view[3] - page.view[1];

                            const scaleX = containerWidth / pageWidth;
                            const scaleY = containerHeight / pageHeight;

                            scale = Math.min(scaleX, scaleY);
                            viewport = page.getViewport({ scale: scale });
                        } else if (zoomMode === 'width') {
                            const container = document.getElementById('pdfContainer');
                            // 为双页模式优化宽度计算：考虑更精确的边距计算，避免溢出
                            const totalMargin = 40; // 容器padding + canvas间距 + 安全边距
                            const containerWidth = (container.clientWidth - totalMargin) / 2;

                            const pageWidth = page.view[2] - page.view[0];
                            scale = Math.min(containerWidth / pageWidth, scale); // 确保不超过容器宽度
                            viewport = page.getViewport({ scale: scale });
                        }
                        // 在自定义缩放模式下，使用当前scale值创建viewport
                        else if (zoomMode === 'custom') {
                            viewport = page.getViewport({ scale: scale });
                        }

                        // 创建canvas元素来显示PDF
                        const canvas = document.createElement('canvas');
                        canvas.className = 'pdf-canvas';
                        const context = canvas.getContext('2d');

                        // 设置canvas尺寸
                        canvas.width = viewport.width;
                        canvas.height = viewport.height;

                        // 添加到容器
                        const pdfViewer = document.getElementById('pdfViewer');
                        // 清空容器内容
                        if (pdfViewer.children.length === 0) {
                            pdfViewer.innerHTML = '';
                        }
                        pdfViewer.appendChild(canvas);

                        // 渲染PDF页面
                        const renderContext = {
                            canvasContext: context,
                            viewport: viewport
                        };
                        page.render(renderContext).promise.then(() => {
                            checkComplete();
                        }).catch(reject);
                    }).catch(reject);
                } else {
                    checkComplete(); // 左页不存在，直接标记完成
                }

                // 渲染右侧页面
                if (rightPageNum <= pdfDoc.numPages) {
                    pdfDoc.getPage(rightPageNum).then(function (page) {
                        // 在自定义缩放模式下，使用当前scale值创建viewport
                        let viewport;
                        if (zoomMode === 'custom') {
                            viewport = page.getViewport({ scale: scale });
                        } else {
                            viewport = page.getViewport({ scale: scale });
                        }

                        // 创建canvas元素来显示PDF
                        const canvas = document.createElement('canvas');
                        canvas.className = 'pdf-canvas';
                        const context = canvas.getContext('2d');

                        // 设置canvas尺寸
                        canvas.width = viewport.width;
                        canvas.height = viewport.height;

                        // 添加到容器
                        const pdfViewer = document.getElementById('pdfViewer');
                        pdfViewer.appendChild(canvas);

                        // 渲染PDF页面
                        const renderContext = {
                            canvasContext: context,
                            viewport: viewport
                        };
                        page.render(renderContext).promise.then(() => {
                            checkComplete();
                        }).catch(reject);
                    }).catch(reject);
                } else {
                    checkComplete(); // 右页不存在，直接标记完成
                }
            });
        }

        // 生成页面缩略图
        function generateThumbnails(pdf) {
            return new Promise((resolve) => {
                const thumbnailList = document.getElementById('thumbnailList');
                thumbnailList.innerHTML = '';

                let completed = 0;
                const total = pdf.numPages;

                // 为每一页生成缩略图
                for (let i = 1; i <= pdf.numPages; i++) {
                    const li = document.createElement('li');
                    li.className = 'thumbnail-item';
                    li.setAttribute('data-page', i);

                    // 创建缩略图容器
                    const pageSpan = document.createElement('span');
                    pageSpan.className = 'thumbnail-page';
                    pageSpan.textContent = i;

                    // 创建缩略图img元素
                    const img = document.createElement('img');
                    img.className = 'thumbnail-img';
                    img.src = '';
                    img.alt = `第${i}页`;

                    li.appendChild(pageSpan);
                    li.appendChild(img);
                    thumbnailList.appendChild(li);

                    // 为缩略图项添加点击事件
                    li.addEventListener('click', function () {
                        if (isLoading) return; // 防止在加载过程中操作

                        const pageNumber = parseInt(this.getAttribute('data-page'));
                        if (!isNaN(pageNumber)) {
                            currentPage = pageNumber;
                            showLoading('正在加载第' + pageNumber + '页...', 50);
                            renderPage(currentPage).then(() => {
                                updateThumbnailHighlight();
                                hideLoading();
                            });
                        }
                    });

                    // 异步渲染缩略图，避免阻塞主线程
                    setTimeout(() => {
                        renderThumbnail(pdf, i, img).then(() => {
                            completed++;
                            if (completed === total) {
                                // 高亮当前页面缩略图
                                updateThumbnailHighlight();
                                resolve();
                            }
                        });
                    }, (i - 1) * 20); // 错开渲染时间，提高性能
                }
            });
        }

        // 渲染缩略图
        function renderThumbnail(pdf, pageNum, imgElement) {
            return new Promise((resolve, reject) => {
                pdf.getPage(pageNum).then(function (page) {
                    // 使用较小的缩放比例生成缩略图
                    const thumbnailScale = 0.15; // 降低缩放比例提高性能
                    const viewport = page.getViewport({ scale: thumbnailScale });

                    // 创建临时canvas来渲染缩略图
                    const canvas = document.createElement('canvas');
                    const context = canvas.getContext('2d');

                    // 设置canvas尺寸
                    canvas.width = viewport.width;
                    canvas.height = viewport.height;

                    // 渲染PDF页面到canvas
                    const renderContext = {
                        canvasContext: context,
                        viewport: viewport
                    };

                    page.render(renderContext).promise.then(function () {
                        // 将canvas内容转换为图片
                        imgElement.src = canvas.toDataURL('image/jpeg', 0.8); // 使用JPEG提高性能
                        resolve();
                    }).catch(reject);
                }).catch(reject);
            });
        }

        // 更新缩略图高亮状态
        function updateThumbnailHighlight() {
            const thumbnails = document.querySelectorAll('.thumbnail-item');
            let activeThumb = null;

            thumbnails.forEach(function (thumb) {
                const pageNum = parseInt(thumb.getAttribute('data-page'));
                if (pageNum === currentPage) {
                    thumb.classList.add('active');
                    activeThumb = thumb;
                } else {
                    thumb.classList.remove('active');
                }
            });

            // 自动滚动到当前页面，使其在可视范围内
            if (activeThumb) {
                const sidebar = document.getElementById('sidebar');
                const sidebarRect = sidebar.getBoundingClientRect();
                const thumbRect = activeThumb.getBoundingClientRect();

                // 检查当前页面是否在可视范围内
                const isVisible = thumbRect.top >= sidebarRect.top &&
                    thumbRect.bottom <= sidebarRect.bottom;

                if (!isVisible) {
                    // 计算需要滚动的位置，使当前页面居中显示在可视区域
                    const sidebarScrollTop = sidebar.scrollTop;
                    const thumbOffsetTop = activeThumb.offsetTop;
                    const sidebarHeight = sidebar.clientHeight;
                    const thumbHeight = activeThumb.offsetHeight;

                    // 计算居中位置
                    const targetScrollTop = thumbOffsetTop - (sidebarHeight / 2) + (thumbHeight / 2);

                    // 平滑滚动到目标位置
                    sidebar.scrollTo({
                        top: targetScrollTop,
                        behavior: 'smooth'
                    });
                }
            }

            // 更新翻页区域状态
            updateFlipAreaStatus();
        }

        // 更新翻页区域状态
        function updateFlipAreaStatus() {
            const prevArea = document.getElementById('prevArea');
            const nextArea = document.getElementById('nextArea');

            if (viewMode === 'single') {
                // 单页模式
                if (currentPage <= 1) {
                    prevArea.classList.add('disabled');
                } else {
                    prevArea.classList.remove('disabled');
                }

                if (currentPage >= pdfDoc.numPages) {
                    nextArea.classList.add('disabled');
                } else {
                    nextArea.classList.remove('disabled');
                }
            } else {
                // 双页模式
                const leftPageNum = currentPage % 2 === 1 ? currentPage : currentPage - 1;
                const rightPageNum = leftPageNum + 1;

                if (leftPageNum <= 1) {
                    prevArea.classList.add('disabled');
                } else {
                    prevArea.classList.remove('disabled');
                }

                if (rightPageNum >= pdfDoc.numPages) {
                    nextArea.classList.add('disabled');
                } else {
                    nextArea.classList.remove('disabled');
                }
            }
        }

        // 全屏模式下的鼠标事件处理
        let hideTimeout;
        let mouseInTopArea = false;

        function setupFullscreenMouseEvents() {
            const trigger = document.getElementById('fullscreenTrigger');
            const header = document.getElementById('header');
            const toolbar = document.getElementById('toolbar');
            const sidebar = document.getElementById('sidebar');
            const menuBtn = document.getElementById('menuBtn');

            // 鼠标进入顶部区域时显示界面元素
            function showUI() {
                mouseInTopArea = true;
                clearTimeout(hideTimeout);
                header.classList.add('show');
                toolbar.classList.add('show');
            }

            // 鼠标离开顶部区域时延迟隐藏界面元素
            function hideUI() {
                mouseInTopArea = false;
                clearTimeout(hideTimeout);
                hideTimeout = setTimeout(() => {
                    if (!mouseInTopArea) {
                        header.classList.remove('show');
                        toolbar.classList.remove('show');
                        // 只有在目录按钮不在显示状态时才隐藏目录
                        if (!sidebar.classList.contains('show')) {
                            sidebar.classList.remove('show');
                        }
                    }
                }, 2000); // 2秒后隐藏
            }

            // 目录按钮点击事件处理
            function toggleSidebar() {
                sidebar.classList.toggle('show');
                // 如果显示目录，也显示头部和工具栏
                if (sidebar.classList.contains('show')) {
                    showUI();
                }
            }

            // 绑定事件
            trigger.addEventListener('mouseenter', showUI);
            trigger.addEventListener('mouseleave', hideUI);

            // 绑定头部事件，防止鼠标在头部时隐藏
            header.addEventListener('mouseenter', showUI);
            header.addEventListener('mouseleave', hideUI);

            // 绑定工具栏事件，防止鼠标在工具栏时隐藏
            toolbar.addEventListener('mouseenter', showUI);
            toolbar.addEventListener('mouseleave', hideUI);

            // 重新绑定目录按钮事件
            menuBtn.removeEventListener('click', handleMenuBtnClick);
            menuBtn.addEventListener('click', toggleSidebar);

            // 保存事件处理函数的引用，以便后续清理
            trigger._showUI = showUI;
            trigger._hideUI = hideUI;
            header._showUI = showUI;
            header._hideUI = hideUI;
            toolbar._showUI = showUI;
            toolbar._hideUI = hideUI;
            menuBtn._toggleSidebar = toggleSidebar;
        }

        function cleanupFullscreenMouseEvents() {
            const trigger = document.getElementById('fullscreenTrigger');
            const header = document.getElementById('header');
            const toolbar = document.getElementById('toolbar');
            const menuBtn = document.getElementById('menuBtn');

            // 清理事件监听
            if (trigger._showUI) {
                trigger.removeEventListener('mouseenter', trigger._showUI);
                trigger.removeEventListener('mouseleave', trigger._hideUI);
            }
            if (header._showUI) {
                header.removeEventListener('mouseenter', header._showUI);
                header.removeEventListener('mouseleave', header._hideUI);
            }
            if (toolbar._showUI) {
                toolbar.removeEventListener('mouseenter', toolbar._showUI);
                toolbar.removeEventListener('mouseleave', toolbar._hideUI);
            }

            // 恢复目录按钮的原始事件
            if (menuBtn._toggleSidebar) {
                menuBtn.removeEventListener('click', menuBtn._toggleSidebar);
                menuBtn.addEventListener('click', handleMenuBtnClick);
            }

            clearTimeout(hideTimeout);
        }

        // ===================绘图功能实现===================

        // 初始化绘图功能
        function initDrawing() {
            drawCanvas = document.getElementById('drawCanvas');
            drawCtx = drawCanvas.getContext('2d');

            // 设置画布尺寸
            updateCanvasSize();

            // 绑定事件
            setupDrawingEvents();
        }

        // 更新画布尺寸
        function updateCanvasSize() {
            const container = document.getElementById('pdfContainer');
            drawCanvas.width = container.clientWidth;
            drawCanvas.height = container.clientHeight;

            // 重绘所有图形
            redrawAll();
        }

        // 设置绘图事件
        function setupDrawingEvents() {
            // 绘图工具按钮事件
            document.querySelectorAll('.draw-tool').forEach(btn => {
                btn.addEventListener('click', function () {
                    const tool = this.getAttribute('data-tool');
                    selectDrawTool(tool);
                });
            });

            // 颜色选择器事件
            document.getElementById('drawColor').addEventListener('change', function () {
                drawColor = this.value;
            });

            // 清除下拉菜单事件
            document.getElementById('clearDropdownBtn').addEventListener('click', function (e) {
                e.stopPropagation();
                const menu = document.getElementById('clearDropdownMenu');
                menu.classList.toggle('show');
            });

            // 清除当前页面事件
            document.getElementById('clearCurrentPage').addEventListener('click', function () {
                clearCurrentPageDrawings();
                document.getElementById('clearDropdownMenu').classList.remove('show');
            });

            // 清除所有页面事件
            document.getElementById('clearAllPages').addEventListener('click', function () {
                if (confirm('确定要清除所有页面的标记吗？此操作不可撤销。')) {
                    clearAllPagesDrawings();
                }
                document.getElementById('clearDropdownMenu').classList.remove('show');
            });

            // 点击其他地方关闭清除下拉菜单
            document.addEventListener('click', function (e) {
                const clearDropdown = document.querySelector('.clear-dropdown');
                const menu = document.getElementById('clearDropdownMenu');
                if (!clearDropdown.contains(e.target)) {
                    menu.classList.remove('show');
                }
            });

            // 画布鼠标事件
            drawCanvas.addEventListener('mousedown', startDrawing);
            drawCanvas.addEventListener('mousemove', draw);
            drawCanvas.addEventListener('mouseup', stopDrawing);
            drawCanvas.addEventListener('mouseout', stopDrawing);

            // 触摸事件（移动设备支持）
            drawCanvas.addEventListener('touchstart', handleTouch);
            drawCanvas.addEventListener('touchmove', handleTouch);
            drawCanvas.addEventListener('touchend', stopDrawing);
        }

        // 选择绘图工具
        function selectDrawTool(tool) {
            // 处理撤销和重做功能
            if (tool === 'undo') {
                undoDrawing();
                return;
            }
            if (tool === 'redo') {
                redoDrawing();
                return;
            }

            // 清除所有按钮的激活状态
            document.querySelectorAll('.draw-tool').forEach(btn => {
                btn.classList.remove('active');
            });

            if (currentTool === tool) {
                // 如果点击的是已激活的工具，则取消选择
                currentTool = null;
                document.body.classList.remove('drawing-mode', 'eraser-mode');
                drawCanvas.classList.remove('drawing');
            } else {
                // 选择新工具
                currentTool = tool;
                document.querySelector(`[data-tool="${tool}"]`).classList.add('active');

                // 清除所有模式类
                document.body.classList.remove('drawing-mode', 'eraser-mode');

                if (tool === 'eraser') {
                    // 橡皮擦模式
                    document.body.classList.add('eraser-mode');
                } else {
                    // 普通绘图模式
                    document.body.classList.add('drawing-mode');
                }

                drawCanvas.classList.add('drawing');
            }

            // 更新撤销重做按钮状态
            updateUndoRedoButtons();
        }

        // 开始绘图
        function startDrawing(e) {
            if (!currentTool) return;

            isDrawing = true;
            const rect = drawCanvas.getBoundingClientRect();
            startX = e.clientX - rect.left;
            startY = e.clientY - rect.top;

            if (currentTool === 'pen') {
                drawCtx.beginPath();
                drawCtx.moveTo(startX, startY);

                // 为画笔创建新的路径
                drawings.push({
                    type: 'pen',
                    color: drawColor,
                    points: [{ x: startX, y: startY }]
                });

                // 画笔工具不在开始时保存历史，而是在结束时保存
            } else if (currentTool === 'eraser') {
                // 橡皮擦工具：查找并删除点击位置的绘图元素
                eraseAtPoint(startX, startY);
            }
        }

        // 绘图过程
        function draw(e) {
            if (!isDrawing || !currentTool) return;

            const rect = drawCanvas.getBoundingClientRect();
            const currentX = e.clientX - rect.left;
            const currentY = e.clientY - rect.top;

            if (currentTool === 'pen') {
                // 画笔工具：实时绘制
                drawCtx.strokeStyle = drawColor;
                drawCtx.lineWidth = 2;
                drawCtx.lineCap = 'round';
                drawCtx.lineTo(currentX, currentY);
                drawCtx.stroke();

                // 添加点到当前路径
                const currentPath = drawings[drawings.length - 1];
                currentPath.points.push({ x: currentX, y: currentY });

                // 为画笔工具实时保存数据（防止绘制中断丢失数据）
                if (currentPath.points.length % 5 === 0) { // 每5个点保存一次，减少频繁操作
                    saveCurrentPageDrawings();
                }
            } else if (currentTool === 'eraser') {
                // 橡皮擦工具：拖拽擦除
                eraseAtPoint(currentX, currentY);
            } else {
                // 其他工具：清除并重绘预览
                redrawAll();
                drawShape(startX, startY, currentX, currentY, currentTool, drawColor);
            }
        }

        // 停止绘图
        function stopDrawing(e) {
            if (!isDrawing || !currentTool) return;

            isDrawing = false;

            if (currentTool === 'eraser') {
                // 橡皮擦结束，保存数据
                saveCurrentPageDrawings();
            } else if (currentTool === 'pen') {
                // 画笔工具在结束时保存历史记录
                saveToHistory();
            } else {
                // 保存其他形状
                const rect = drawCanvas.getBoundingClientRect();
                const endX = e.clientX - rect.left;
                const endY = e.clientY - rect.top;

                drawings.push({
                    type: currentTool,
                    color: drawColor,
                    startX: startX,
                    startY: startY,
                    endX: endX,
                    endY: endY
                });

                // 保存到历史记录
                saveToHistory();
            }

            // 绘图完成后自动保存当前页面的绘图数据
            saveCurrentPageDrawings();

            // 更新撤销重做按钮状态
            updateUndoRedoButtons();
            // 同时更新右键菜单状态
            updateContextMenuState();
        }

        // 绘制形状
        function drawShape(x1, y1, x2, y2, type, color) {
            drawCtx.strokeStyle = color;
            drawCtx.lineWidth = 2;
            drawCtx.lineCap = 'round';

            switch (type) {
                case 'line':
                    drawCtx.beginPath();
                    drawCtx.moveTo(x1, y1);
                    drawCtx.lineTo(x2, y2);
                    drawCtx.stroke();
                    break;

                case 'rectangle':
                    drawCtx.beginPath();
                    drawCtx.rect(x1, y1, x2 - x1, y2 - y1);
                    drawCtx.stroke();
                    break;

                case 'circle':
                    const radius = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
                    drawCtx.beginPath();
                    drawCtx.arc(x1, y1, radius, 0, 2 * Math.PI);
                    drawCtx.stroke();
                    break;

                case 'arrow':
                    drawArrow(x1, y1, x2, y2, color);
                    break;
            }
        }

        // 绘制箭头
        function drawArrow(x1, y1, x2, y2, color) {
            drawCtx.strokeStyle = color;
            drawCtx.fillStyle = color;
            drawCtx.lineWidth = 2;

            // 绘制箭头主体
            drawCtx.beginPath();
            drawCtx.moveTo(x1, y1);
            drawCtx.lineTo(x2, y2);
            drawCtx.stroke();

            // 计算箭头角度
            const angle = Math.atan2(y2 - y1, x2 - x1);
            const arrowLength = 15;
            const arrowAngle = Math.PI / 6;

            // 绘制箭头
            drawCtx.beginPath();
            drawCtx.moveTo(x2, y2);
            drawCtx.lineTo(
                x2 - arrowLength * Math.cos(angle - arrowAngle),
                y2 - arrowLength * Math.sin(angle - arrowAngle)
            );
            drawCtx.moveTo(x2, y2);
            drawCtx.lineTo(
                x2 - arrowLength * Math.cos(angle + arrowAngle),
                y2 - arrowLength * Math.sin(angle + arrowAngle)
            );
            drawCtx.stroke();
        }

        // 撤销重做功能的核心函数

        // 保存当前状态到历史记录
        function saveToHistory() {
            // 深拷贝当前绘图数据
            const currentState = JSON.parse(JSON.stringify(drawings));

            // 如果不是在末尾，删除之后的所有历史
            if (historyIndex < drawingHistory.length - 1) {
                drawingHistory = drawingHistory.slice(0, historyIndex + 1);
            }

            // 添加新状态
            drawingHistory.push(currentState);
            historyIndex++;

            // 限制历史记录数量
            if (drawingHistory.length > maxHistoryLength) {
                drawingHistory.shift();
                historyIndex--;
            }

            updateUndoRedoButtons();
            // 同时更新右键菜单状态
            updateContextMenuState();
        }

        // 撤销操作
        function undoDrawing() {
            if (historyIndex > 0) {
                historyIndex--;
                drawings = JSON.parse(JSON.stringify(drawingHistory[historyIndex]));
                redrawAll();
                saveCurrentPageDrawings();
                updateUndoRedoButtons();
                // 同时更新右键菜单状态
                updateContextMenuState();
            }
        }

        // 重做操作
        function redoDrawing() {
            if (historyIndex < drawingHistory.length - 1) {
                historyIndex++;
                drawings = JSON.parse(JSON.stringify(drawingHistory[historyIndex]));
                redrawAll();
                saveCurrentPageDrawings();
                updateUndoRedoButtons();
                // 同时更新右键菜单状态
                updateContextMenuState();
            }
        }

        // 更新撤销重做按钮状态
        function updateUndoRedoButtons() {
            const undoBtn = document.querySelector('[data-tool="undo"]');
            const redoBtn = document.querySelector('[data-tool="redo"]');

            if (undoBtn) {
                undoBtn.disabled = historyIndex <= 0;
            }

            if (redoBtn) {
                redoBtn.disabled = historyIndex >= drawingHistory.length - 1;
            }
        }

        // 初始化历史记录（在页面切换时调用）
        function initializeHistory() {
            drawingHistory = [JSON.parse(JSON.stringify(drawings))];
            historyIndex = 0;
            updateUndoRedoButtons();
            // 同时更新右键菜单状态
            updateContextMenuState();
        }

        // 橡皮擦功能：擦除指定点附近的绘图
        function eraseAtPoint(x, y) {
            const eraseRadius = 20; // 擦除半径
            let hasErased = false;

            // 从后往前遍历，优先擦除最新的绘图
            for (let i = drawings.length - 1; i >= 0; i--) {
                const drawing = drawings[i];
                let shouldErase = false;

                if (drawing.type === 'pen') {
                    // 检查自由线条的每个点
                    for (let point of drawing.points) {
                        const distance = Math.sqrt(Math.pow(point.x - x, 2) + Math.pow(point.y - y, 2));
                        if (distance <= eraseRadius) {
                            shouldErase = true;
                            break;
                        }
                    }
                } else {
                    // 检查几何形状（线条、矩形、圆形、箭头）
                    // 简化处理：检查起点和终点是否在擦除范围内
                    const startDistance = Math.sqrt(Math.pow(drawing.startX - x, 2) + Math.pow(drawing.startY - y, 2));
                    const endDistance = Math.sqrt(Math.pow(drawing.endX - x, 2) + Math.pow(drawing.endY - y, 2));

                    if (startDistance <= eraseRadius || endDistance <= eraseRadius) {
                        shouldErase = true;
                    } else if (drawing.type === 'line' || drawing.type === 'arrow') {
                        // 对于线条和箭头，检查点到线段的距离
                        const lineDistance = pointToLineDistance(x, y, drawing.startX, drawing.startY, drawing.endX, drawing.endY);
                        if (lineDistance <= eraseRadius) {
                            shouldErase = true;
                        }
                    }
                }

                if (shouldErase) {
                    drawings.splice(i, 1);
                    hasErased = true;
                }
            }

            if (hasErased) {
                redrawAll();
                // 保存到历史记录
                saveToHistory();
            }
        }

        // 计算点到线段的距离
        function pointToLineDistance(px, py, x1, y1, x2, y2) {
            const A = px - x1;
            const B = py - y1;
            const C = x2 - x1;
            const D = y2 - y1;

            const dot = A * C + B * D;
            const lenSq = C * C + D * D;
            let param = -1;
            if (lenSq !== 0) {
                param = dot / lenSq;
            }

            let xx, yy;
            if (param < 0) {
                xx = x1;
                yy = y1;
            } else if (param > 1) {
                xx = x2;
                yy = y2;
            } else {
                xx = x1 + param * C;
                yy = y1 + param * D;
            }

            const dx = px - xx;
            const dy = py - yy;
            return Math.sqrt(dx * dx + dy * dy);
        }

        // 重绘所有图形
        function redrawAll() {
            drawCtx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);

            drawings.forEach(drawing => {
                if (drawing.type === 'pen') {
                    // 绘制自由线条
                    if (drawing.points.length > 1) {
                        drawCtx.strokeStyle = drawing.color;
                        drawCtx.lineWidth = 2;
                        drawCtx.lineCap = 'round';
                        drawCtx.beginPath();
                        drawCtx.moveTo(drawing.points[0].x, drawing.points[0].y);

                        for (let i = 1; i < drawing.points.length; i++) {
                            drawCtx.lineTo(drawing.points[i].x, drawing.points[i].y);
                        }
                        drawCtx.stroke();
                    }
                } else {
                    // 绘制几何形状
                    drawShape(
                        drawing.startX, drawing.startY,
                        drawing.endX, drawing.endY,
                        drawing.type, drawing.color
                    );
                }
            });
        }

        // 清除当前页面绘图（新函数，不再使用clearAllDrawings）
        function clearCurrentPageDrawings() {
            drawings = [];
            if (drawCtx) {
                drawCtx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);
            }
            // 清除当前页面的存储数据
            if (currentPage) {
                delete pageDrawings[currentPage];
                saveDrawingsToLocal();
            }
            // 重置历史记录
            initializeHistory();
        }

        // 清除所有页面绘图（新函数）
        function clearAllPagesDrawings() {
            // 清除当前页面的显示
            drawings = [];
            if (drawCtx) {
                drawCtx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);
            }
            // 清除所有页面的存储数据
            pageDrawings = {};
            saveDrawingsToLocal();
            // 重置历史记录
            initializeHistory();
        }

        // 清除当前页面绘图（旧函数，保持向后兼容）
        function clearAllDrawings() {
            clearCurrentPageDrawings();
        }

        // 处理触摸事件
        function handleTouch(e) {
            e.preventDefault();
            const touch = e.touches[0];
            if (touch) {
                const mouseEvent = new MouseEvent(e.type === 'touchstart' ? 'mousedown' :
                    e.type === 'touchmove' ? 'mousemove' : 'mouseup', {
                    clientX: touch.clientX,
                    clientY: touch.clientY
                });
                drawCanvas.dispatchEvent(mouseEvent);
            }
        }

        // 在页面加载完成后初始化绘图功能
        document.addEventListener('DOMContentLoaded', function () {
            initDrawing();
            initContextMenu();

            // 监听窗口大小变化，更新画布尺寸
            window.addEventListener('resize', updateCanvasSize);

            // 刷新页面时清除所有保存的绘图数据（不加载旧数据）
            clearAllDrawingsData();

            // 页面卸载时保存当前页面的绘图数据（不清空，暂时保存）
            window.addEventListener('beforeunload', function () {
                saveCurrentPageDrawings();
            });
        });

        // 保存当前页面的绘图数据（用于其他情况，如绘图完成后、页面关闭时）
        function saveCurrentPageDrawings() {
            if (currentPage) { // 只要有当前页面就保存，即使没有绘图
                pageDrawings[currentPage] = JSON.parse(JSON.stringify(drawings));
                // 保存到本地存储
                saveDrawingsToLocal();
            }
        }

        // 加载当前页面的绘图数据
        function loadCurrentPageDrawings(pageNum) {
            // 清空当前绘图
            drawings = [];
            if (drawCtx) {
                drawCtx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);
            }

            // 加载指定页面的绘图数据（如果存在）
            if (pageDrawings[pageNum]) {
                drawings = JSON.parse(JSON.stringify(pageDrawings[pageNum]));
            }

            // 初始化历史记录
            initializeHistory();

            // 重新绘制该页面的所有图形
            setTimeout(() => {
                if (drawCtx) {
                    redrawAll();
                }
            }, 100);
        }

        // 保存绘图数据到本地存储
        function saveDrawingsToLocal() {
            try {
                localStorage.setItem('pdfDrawings', JSON.stringify(pageDrawings));
            } catch (e) {
                console.warn('无法保存绘图数据到本地存储:', e);
            }
        }

        // 从本地存储加载绘图数据（不自动调用，只在明确需要时才加载）
        function loadDrawingsFromLocal() {
            try {
                const saved = localStorage.getItem('pdfDrawings');
                if (saved) {
                    pageDrawings = JSON.parse(saved);
                    // 如果当前已有页面，加载该页面的绘图
                    if (currentPage) {
                        loadCurrentPageDrawings(currentPage);
                    }
                }
            } catch (e) {
                console.warn('无法从本地存储加载绘图数据:', e);
                pageDrawings = {};
            }
        }

        // 清除所有绘图数据（包括本地存储）
        function clearAllDrawingsData() {
            pageDrawings = {};
            drawings = [];
            if (drawCtx) {
                drawCtx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);
            }
            // 清除本地存储
            try {
                localStorage.removeItem('pdfDrawings');
            } catch (e) {
                console.warn('无法清除本地存储的绘图数据:', e);
            }
        }

        // 在翻页时清除绘图（保持向后兼容）
        function clearDrawingsOnPageChange() {
            // 这个函数现在由saveCurrentPageDrawings和loadCurrentPageDrawings代替
            // 保留空函数以防其他地方调用
        }

        // 右键菜单功能
        function initContextMenu() {
            const contextMenu = document.getElementById('contextMenu');
            const pdfContainer = document.getElementById('pdfContainer');

            // 监听右键点击事件
            pdfContainer.addEventListener('contextmenu', function (e) {
                e.preventDefault();
                showContextMenu(e.clientX, e.clientY);
            });

            // 点击其他地方隐藏菜单
            document.addEventListener('click', function (e) {
                if (!contextMenu.contains(e.target)) {
                    hideContextMenu();
                }
            });

            // 为子菜单添加智能定位功能
            document.querySelectorAll('.context-menu-submenu').forEach(submenuItem => {
                submenuItem.addEventListener('mouseenter', function () {
                    const submenu = this.querySelector('.context-submenu');
                    if (submenu) {
                        // 重置之前的定位类
                        submenu.classList.remove('position-up', 'position-left');

                        // 延迟一帧来确保submenu已经显示
                        setTimeout(() => {
                            const rect = submenu.getBoundingClientRect();
                            const windowWidth = window.innerWidth;
                            const windowHeight = window.innerHeight;

                            // 检查是否超出右边界，如果是则向左显示
                            if (rect.right > windowWidth) {
                                submenu.classList.add('position-left');
                            }

                            // 检查是否超出底部边界，如果是则向上显示
                            if (rect.bottom > windowHeight) {
                                submenu.classList.add('position-up');
                            }
                        }, 10);
                    }
                });
            });

            // 监听菜单项点击
            contextMenu.addEventListener('click', function (e) {
                const item = e.target.closest('.context-menu-item');
                if (item && item.dataset.action && !item.classList.contains('disabled')) {
                    handleContextMenuAction(item.dataset.action, item.dataset);
                    hideContextMenu();
                }
            });

            // ESC 键隐藏菜单
            document.addEventListener('keydown', function (e) {
                if (e.key === 'Escape') {
                    hideContextMenu();
                }
            });

            // 添加键盘快捷键支持
            document.addEventListener('keydown', function (e) {
                if (e.ctrlKey || e.metaKey) {
                    switch (e.key.toLowerCase()) {
                        case 'z':
                            if (e.shiftKey) {
                                e.preventDefault();
                                redoDrawing();
                            } else {
                                e.preventDefault();
                                undoDrawing();
                            }
                            break;
                        case 'y':
                            e.preventDefault();
                            redoDrawing();
                            break;
                    }
                }
            });
        }

        // 显示右键菜单
        function showContextMenu(x, y) {
            const contextMenu = document.getElementById('contextMenu');

            // 更新菜单状态（确保状态最新）
            updateContextMenuState();

            // 设置位置
            contextMenu.style.left = x + 'px';
            contextMenu.style.top = y + 'px';
            contextMenu.classList.add('show');

            // 调整位置以确保不超出屏幕
            const rect = contextMenu.getBoundingClientRect();
            const windowWidth = window.innerWidth;
            const windowHeight = window.innerHeight;

            if (rect.right > windowWidth) {
                contextMenu.style.left = (windowWidth - rect.width - 10) + 'px';
            }
            if (rect.bottom > windowHeight) {
                contextMenu.style.top = (windowHeight - rect.height - 10) + 'px';
            }
        }

        // 隐藏右键菜单
        function hideContextMenu() {
            const contextMenu = document.getElementById('contextMenu');
            contextMenu.classList.remove('show');
        }

        // 更新右键菜单状态
        function updateContextMenuState() {
            // 更新翻页按钮状态
            const firstPageBtn = document.querySelector('[data-action="firstPage"]');
            const prevPageBtn = document.querySelector('[data-action="prevPage"]');
            const nextPageBtn = document.querySelector('[data-action="nextPage"]');
            const lastPageBtn = document.querySelector('[data-action="lastPage"]');

            if (firstPageBtn && prevPageBtn) {
                if (currentPage <= 1) {
                    firstPageBtn.classList.add('disabled');
                    prevPageBtn.classList.add('disabled');
                } else {
                    firstPageBtn.classList.remove('disabled');
                    prevPageBtn.classList.remove('disabled');
                }
            }

            if (nextPageBtn && lastPageBtn && pdfDoc) {
                if (currentPage >= pdfDoc.numPages) {
                    nextPageBtn.classList.add('disabled');
                    lastPageBtn.classList.add('disabled');
                } else {
                    nextPageBtn.classList.remove('disabled');
                    lastPageBtn.classList.remove('disabled');
                }
            }

            // 更新当前选中的绘图工具
            document.querySelectorAll('[data-action="selectTool"]').forEach(btn => {
                const tool = btn.dataset.tool;
                if (currentTool === tool) {
                    btn.style.backgroundColor = '#e3f2fd';
                    btn.style.color = '#007bff';
                } else {
                    btn.style.backgroundColor = '';
                    btn.style.color = '';
                }
            });

            // 更新视图模式文本
            const toggleViewModeBtn = document.querySelector('[data-action="toggleViewMode"]');
            if (toggleViewModeBtn) {
                const textSpan = toggleViewModeBtn.querySelector('.context-menu-text');
                if (textSpan) {
                    textSpan.textContent = viewMode === 'single' ? '切换到双页模式' : '切换到单页模式';
                }
            }

            // 更新目录显示状态文本
            const toggleSidebarBtn = document.querySelector('[data-action="toggleSidebar"]');
            if (toggleSidebarBtn) {
                const textSpan = toggleSidebarBtn.querySelector('.context-menu-text');
                const sidebar = document.getElementById('sidebar');
                if (textSpan && sidebar) {
                    const isHidden = sidebar.classList.contains('hidden');
                    textSpan.textContent = isHidden ? '显示目录' : '隐藏目录';
                }
            }

            // 更新全屏状态文本
            const toggleFullscreenBtn = document.querySelector('[data-action="toggleFullscreen"]');
            if (toggleFullscreenBtn) {
                const textSpan = toggleFullscreenBtn.querySelector('.context-menu-text');
                if (textSpan) {
                    textSpan.textContent = isFullscreen ? '退出全屏' : '全屏模式';
                }
            }
        }

        // 处理右键菜单操作
        function handleContextMenuAction(action, data) {
            switch (action) {
                // 绘图工具
                case 'selectTool':
                    selectDrawTool(data.tool);
                    break;

                // 缩放控制
                case 'setZoom':
                    if (data.zoom === 'fit' || data.zoom === 'width') {
                        zoomMode = data.zoom;
                        if (typeof renderPage === 'function') {
                            renderPage(currentPage);
                        }
                    } else {
                        const zoomValue = parseInt(data.zoom);
                        if (zoomValue) {
                            zoomMode = 'custom';
                            scale = zoomValue / 100;
                            if (typeof renderPage === 'function') {
                                renderPage(currentPage);
                            }
                        }
                    }
                    // 更新缩放下拉框
                    if (typeof updateZoomSelect === 'function') {
                        updateZoomSelect();
                    }
                    break;

                // 翻页控制
                case 'firstPage':
                    if (currentPage > 1 && typeof handleFirstPage === 'function') {
                        handleFirstPage();
                    }
                    break;
                case 'prevPage':
                    if (currentPage > 1 && typeof handlePrevPage === 'function') {
                        handlePrevPage();
                    }
                    break;
                case 'nextPage':
                    if (pdfDoc && currentPage < pdfDoc.numPages && typeof handleNextPage === 'function') {
                        handleNextPage();
                    }
                    break;
                case 'lastPage':
                    if (pdfDoc && currentPage < pdfDoc.numPages && typeof handleLastPage === 'function') {
                        handleLastPage();
                    }
                    break;
                case 'toggleViewMode':
                    // 切换单页/双页模式
                    if (viewMode === 'single') {
                        document.getElementById('doublePage').click();
                    } else {
                        document.getElementById('singlePage').click();
                    }
                    break;

                // 清除功能
                case 'clearCurrentPage':
                    clearCurrentPageDrawings();
                    break;
                case 'clearAllPages':
                    if (confirm('确定要清除所有页面的标记吗？此操作不可撤销。')) {
                        clearAllPagesDrawings();
                    }
                    break;

                // 其他功能
                case 'toggleSidebar':
                    document.getElementById('menuBtn').click();
                    break;
                case 'toggleFullscreen':
                    document.getElementById('fullscreenBtn').click();
                    break;
                case 'download':
                    document.getElementById('downloadBtn').click();
                    break;
            }
        }
    </script>

    <!-- 右键菜单 -->
    <div id="contextMenu" class="context-menu">
        <!-- 绘图工具子菜单 -->
        <div class="context-menu-item context-menu-submenu" id="drawToolsSubmenu">
            <span class="context-menu-icon">✏️</span>
            <span class="context-menu-text">绘图工具</span>
            <div class="context-submenu">
                <button class="context-menu-item" data-action="selectTool" data-tool="pen">
                    <span class="context-menu-icon">✏️</span>
                    <span class="context-menu-text">画笔</span>
                </button>
                <button class="context-menu-item" data-action="selectTool" data-tool="line">
                    <span class="context-menu-icon">📏</span>
                    <span class="context-menu-text">直线</span>
                </button>
                <button class="context-menu-item" data-action="selectTool" data-tool="rectangle">
                    <span class="context-menu-icon">⬜</span>
                    <span class="context-menu-text">矩形</span>
                </button>
                <button class="context-menu-item" data-action="selectTool" data-tool="circle">
                    <span class="context-menu-icon">⭕</span>
                    <span class="context-menu-text">圆形</span>
                </button>
                <button class="context-menu-item" data-action="selectTool" data-tool="arrow">
                    <span class="context-menu-icon">➡️</span>
                    <span class="context-menu-text">箭头</span>
                </button>
                <button class="context-menu-item" data-action="selectTool" data-tool="eraser">
                    <span class="context-menu-icon">🧹</span>
                    <span class="context-menu-text">橡皮擦</span>
                </button>
            </div>
        </div>



        <!-- 缩放控制子菜单 -->
        <div class="context-menu-item context-menu-submenu" id="zoomSubmenu">
            <span class="context-menu-icon">🔍</span>
            <span class="context-menu-text">缩放</span>
            <div class="context-submenu">
                <button class="context-menu-item" data-action="setZoom" data-zoom="fit">
                    <span class="context-menu-text">适应屏幕</span>
                </button>
                <button class="context-menu-item" data-action="setZoom" data-zoom="width">
                    <span class="context-menu-text">适应宽度</span>
                </button>
                <div class="context-menu-divider"></div>
                <button class="context-menu-item" data-action="setZoom" data-zoom="50">
                    <span class="context-menu-text">50%</span>
                </button>
                <button class="context-menu-item" data-action="setZoom" data-zoom="75">
                    <span class="context-menu-text">75%</span>
                </button>
                <button class="context-menu-item" data-action="setZoom" data-zoom="100">
                    <span class="context-menu-text">100%</span>
                </button>
                <button class="context-menu-item" data-action="setZoom" data-zoom="125">
                    <span class="context-menu-text">125%</span>
                </button>
                <button class="context-menu-item" data-action="setZoom" data-zoom="150">
                    <span class="context-menu-text">150%</span>
                </button>
                <button class="context-menu-item" data-action="setZoom" data-zoom="200">
                    <span class="context-menu-text">200%</span>
                </button>
            </div>
        </div>

        <!-- 翻页控制子菜单 -->
        <div class="context-menu-item context-menu-submenu" id="pageSubmenu">
            <span class="context-menu-icon">📄</span>
            <span class="context-menu-text">页面导航</span>
            <div class="context-submenu">
                <button class="context-menu-item" data-action="firstPage">
                    <span class="context-menu-icon">⇤</span>
                    <span class="context-menu-text">首页</span>
                    <span class="context-menu-shortcut">Home</span>
                </button>
                <button class="context-menu-item" data-action="prevPage">
                    <span class="context-menu-icon">◀</span>
                    <span class="context-menu-text">上一页</span>
                    <span class="context-menu-shortcut">←</span>
                </button>
                <button class="context-menu-item" data-action="nextPage">
                    <span class="context-menu-icon">▶</span>
                    <span class="context-menu-text">下一页</span>
                    <span class="context-menu-shortcut">→</span>
                </button>
                <button class="context-menu-item" data-action="lastPage">
                    <span class="context-menu-icon">⇥</span>
                    <span class="context-menu-text">尾页</span>
                    <span class="context-menu-shortcut">End</span>
                </button>
                <div class="context-menu-divider"></div>
                <button class="context-menu-item" data-action="toggleViewMode">
                    <span class="context-menu-icon">🔄</span>
                    <span class="context-menu-text">切换视图模式</span>
                </button>
            </div>
        </div>

        <div class="context-menu-divider"></div>

        <!-- 清除功能子菜单 -->
        <div class="context-menu-item context-menu-submenu" id="clearSubmenu">
            <span class="context-menu-icon">🗑️</span>
            <span class="context-menu-text">清除标记</span>
            <div class="context-submenu">
                <button class="context-menu-item" data-action="clearCurrentPage">
                    <span class="context-menu-text">清除当前页</span>
                </button>
                <button class="context-menu-item" data-action="clearAllPages">
                    <span class="context-menu-text">清除所有页</span>
                </button>
            </div>
        </div>

        <!-- 其他功能 -->
        <button class="context-menu-item" data-action="toggleSidebar">
            <span class="context-menu-icon">📁</span>
            <span class="context-menu-text">显示目录</span>
        </button>
        <button class="context-menu-item" data-action="toggleFullscreen">
            <span class="context-menu-icon">⛶️</span>
            <span class="context-menu-text">全屏模式</span>
            <span class="context-menu-shortcut">F11</span>
        </button>
        <button class="context-menu-item" data-action="download">
            <span class="context-menu-icon">⬇️</span>
            <span class="context-menu-text">下载 PDF</span>
        </button>
    </div>
</body>

</html>